import { getToken } from '@/utils/storage'
import { Message } from 'element-ui'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 使用 () => import('@/views/login') 语法可以实现懒加载 直接在语法中引入
const routes = [
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/',
    component: () => import('@/views/layout'),
    children: [
      {
        path: '/dashboard',
        component: () => import('@/views/dashboard')
      },
      {
        path: '/article',
        component: () => import('@/views/article')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const token = getToken()
  // 判断 没有 token 并且 访问的页面不是 login 直接返回首页 否则直接放行
  // 逻辑 && 只有都为true才返回true
  if (!token && to.path !== '/login') {
    next('/login')
    Message.warning('亲,您还未登录,请登录后访问')
  }
  next()
})

export default router
